<?php
namespace app\admin\controller;
use think\Controller;
use think\Exception;
use think\exception\ErrorException;
use think\Log;
use app\admin\model\Goods as GoodsModel;

class Common extends Controller
{
    public function _initialize()
    {
        if(!session('usermail') || !session('kouling')){
           $this->error('请登录',url('login/index')); 
        }
	
    }

    /**
     * @Notes:   通用物料搜索API（导购）采集
     * @User:    this邹
     * @CreateDate:  2019/2/27 0027 17:15
     * @param $info
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function dgMaterialOptional($info)
    {
        $cid = $info['cid'];
        $map_data = array();

        vendor('taobao_sdk.top.TopClient');
        vendor('taobao_sdk.top.ResultSet');
        vendor('taobao_sdk.top.RequestCheckUtil');
        vendor('taobao_sdk.top.TopLogger');
        vendor('taobao_sdk.top.request.TbkDgMaterialOptionalRequest');

        try{
            $c = new \TopClient();
            $c->appkey = config('web.WEB_TBKEY');//淘宝KEY
            $c->secretKey = config('web.WEB_TBSECREC');//淘宝SECREC
            $req = new \TbkDgMaterialOptionalRequest;
            for ($page_no = 1; $page_no <= $info['page_no']; $page_no++) {
                $req->setAdzoneId(get_adzoneid(config('web.WEB_YHQPID')));//高拥PID  获取adzoneid
    //            $req->setStartDsr("10");//店铺dsr评分，筛选高于等于当前设置的店铺dsr评分的商品0-50000之间
                $req->setPageSize($info["page_size"]);//页大小，默认20，1~100
                $req->setPageNo($page_no);//第几页，默认：1
                $req->setPlatform("1");// 链接形式：1：PC，2：无线，默认：１
                $req->setEndTkRate($info["end_tk_rate"]);//淘客佣金比率上限，如：1234表示12.34%
                $req->setStartTkRate($info["start_tk_rate"]);//淘客佣金比率下限，如：1234表示12.34%
                $req->setEndPrice($info["end_price"]);//折扣价范围上限，单位：元
                $req->setStartPrice($info["start_price"]);//折扣价范围下限，单位：元
                $req->setIsTmall($info["is_tmall"]);//是否商城商品，设置为true表示该商品是属于淘宝商城商品，设置为false或不设置表示不判断这个属性
                $req->setSort($info["sort"]);//排序_des（降序），排序_asc（升序），销量（total_sales），淘客佣金比率（tk_rate）， 累计推广量（tk_total_sales），总支出佣金（tk_total_commi），价格（price）
                $req->setCat($info["catIds"]);//后台类目ID，用,分割，最大10个，该ID可以通过taobao.itemcats.get接口获取到
                $req->setQ($info["keyword"]);//查询词
                $req->setHasCoupon($info["has_coupon"]);//是否有优惠券，设置为true表示该商品有优惠券，设置为false或不设置表示不判断这个属性
                $req->setNeedFreeShipment($info["need_free_shipment"]);//是否包邮，true表示包邮，空或false表示不限
                $req->setNpxLevel($info["npx_level"]);//牛皮癣程度，取值：1:不限，2:无，3:轻微
                $resp = $c->execute($req);
                $resp = object_to_array($resp);

                foreach ($resp['result_list']['map_data'] as $items) {
                    array_push($map_data, $items);
                }
            }

        }catch(Exception $e){
            Log::write('此dgMaterialOptional搜索数据异常'.$e->getMessage(),'error');
            return ['code' => 300];
        }


        $item = array();
        foreach ($map_data as $mapKey => $mapVal) {
            $item[$mapKey]['title'] = $mapVal['title'];//产品标题
            $item[$mapKey]['uid'] = session('userid');//发布者ID
            $item[$mapKey]['cid'] = $cid;//当前采集的分类ID
            $item[$mapKey]['pic'] = str_replace('https', 'http', $mapVal['pict_url']);//产品主图
            $item[$mapKey]['numIid'] = $mapVal['item_id'];//产品ID
            $item[$mapKey]['couponTotalcount'] = $mapVal['coupon_total_count'];//优惠券总量
            $item[$mapKey]['couponRemaincount'] = $mapVal['coupon_remain_count'];//优惠券剩余量
            $item[$mapKey]['couponAmount'] = get_word($mapVal['coupon_info'], '减', '元');//优惠券面额
            $item[$mapKey]['price'] = $mapVal['reserve_price'];//产品一口价格
            $item[$mapKey]['couponPrice'] = $mapVal['zk_final_price'];//产品折扣价格
            $item[$mapKey]['couponRate'] = round($mapVal['zk_final_price'] - $item[$mapKey]['couponAmount'],1);//产品劵后价=产品折扣价格-优惠券面额
            $item[$mapKey]['volume'] = $mapVal['volume'];//30天销量
            $item[$mapKey]['nick'] = $mapVal['shop_title'];//店铺名称
            $item[$mapKey]['sellerId'] = $mapVal['seller_id'];//卖家id
            $item[$mapKey]['clickUrl'] = isset($mapVal['coupon_share_url']) ? "https:" . $mapVal['coupon_share_url'] : "https:" . $mapVal['url'];// coupon_share_url:券二合一页面链接  url:推广链接
            $item[$mapKey]['commissionRate'] = $mapVal['commission_rate'] / 100;//佣金比率 1550表示15.5%
            $item[$mapKey]['commission'] = round($item[$mapKey]['couponRate'] * ($item[$mapKey]['commissionRate']), 1) / 100;//总佣金=产品劵后价*佣金比率/100
            $item[$mapKey]['commissionUser'] = round($item[$mapKey]['commission'] * 80 / 100, 1);//用户所得佣金
            $item[$mapKey]['userType'] = "0";//卖家类型  0淘宝
            $item[$mapKey]['description'] = $item[$mapKey]['title'] . '，现价只需要' . $mapVal['zk_final_price'] . '元，领券后下单还可优惠' . $item[$mapKey]['couponAmount'] . '元，赶紧抢购吧！';//描述
            $item[$mapKey]['keywords'] = implode(',', get_tags($item[$mapKey]['title']));//关键词
            $item[$mapKey]['couponStartTime'] = empty(strtotime($mapVal['coupon_start_time'])) ? time() : strtotime($mapVal['coupon_start_time']);//优惠券开始时间
            $item[$mapKey]['couponEndTime'] = empty(strtotime($mapVal['coupon_end_time'])) ? time() + (60 * 60 * 48) : strtotime($mapVal['coupon_end_time']);//优惠券结束时间
            $item[$mapKey]['addTime'] = time();//添加时间
        }

        if ($item) {
            // 保存采集数据
            $goodsModel = new GoodsModel();
            $isTrue = $goodsModel->saveGoodsItem($item);
            if($isTrue['start_code']){
                return ['code' => 200,'msg'=>'SUCCESS','num'=>$isTrue['num']];
            }else{
                return ['code' => 400,'msg'=>'数据存储异常！'];
            }
        }
    }

    /**
     * 超级搜索的商品生成淘口令
     * @param $clickUrl 券二合一页面链接
     * @param $title 标题
     * @param $pic 商品主图
     * @param $url 推广连接
     * @return \think\response\Json
     */
    public function taobaoToken($clickUrl,$title,$pic,$url)
    {
        vendor('taobao.TopClient');
        vendor('taobao.ResultSet');
        vendor('taobao.RequestCheckUtil');
        vendor('taobao.TopLogger');
        vendor('taobao.domain.GenPwdIsvParamDto');
        vendor('taobao.request.TbkTpwdCreateRequest');
        vendor('taobao.request.WirelessShareTpwdCreateRequest');

        try{
            // 生成淘口令 - 此商品 有 券二合一页面链接则生成淘口令
            if ($clickUrl) {
                $clickUrl = 'https:'.$clickUrl;

                $c = new \TopClient();
                $c->appkey = config('web.WEB_TBKEY');//淘宝KEY
                $c->secretKey = config('web.WEB_TBSECREC');//淘宝客SECREC
                $req = new \TbkTpwdCreateRequest;
                $req->setText($title);
                $req->setUrl($clickUrl);
                $req->setLogo($pic);
                $req->setUserId(config('web.WEB_TBUID'));//阿里妈妈UID
                $req->setExt("{}");
                $resp = $c->execute($req);
                $tao_token = object_to_array($resp)['data']['model'];
            }

            // 生成淘口令 - 此商品 没有 券二合一页面链接 则用 推广链接 生成淘口令

            if ($url) {
//            $url = str_replace(" ","+",$url);
                $c = new \TopClient;
                $c->appkey = config('web.WEB_TBKEY');
                $c->secretKey = config('web.WEB_TBSECREC');
                $req = new \WirelessShareTpwdCreateRequest;
                $tpwd_param = new \GenPwdIsvParamDto;
                $tpwd_param->logo = $pic;
                $tpwd_param->url = $url;
                $tpwd_param->text = $title;
                $tpwd_param->user_id = config('web.WEB_TBUID');
                $req->setTpwdParam(json_encode($tpwd_param));
                $resp = $c->execute($req);
                $tao_token = object_to_array($resp)['model'];
            }
        }catch(ErrorException $errorException){
//            $tao_token = '没有淘口令';
            return '没有淘口令';
        }
        if($tao_token){
            return $tao_token;
        }else{
//            $tao_token = '没有淘口令';
            return '没有淘口令';
        }

    }

    /**
     * 获取优惠卷信息
     * @param $num_iid      商品id
     * @param $coupon_id    优惠卷加密串id
     * @return array
     */
    public function getCoupon($num_iid,$coupon_id)
    {

        if($coupon_id){
            try{
                vendor('taobao.TopClient');
                vendor('taobao.ResultSet');
                vendor('taobao.request.TbkCouponGetRequest');
                $c = new \TopClient;
                $c->appkey = config('web.WEB_TBKEY');//淘宝KEY
                $c->secretKey = config('web.WEB_TBSECREC');//淘宝客SECREC
                $req = new \TbkCouponGetRequest;
                $req->setItemId($num_iid);
                $req->setActivityId($coupon_id);
                $resp = $c->execute($req);
                $resp = object_to_array($resp);
                return $resp['data'];
            }catch(ErrorException $errorException){
                dump('错');die;
                return [];
            }

        }
        return [];
    }

    /**
     * 验证是否登录阿里妈妈cookie
     * @return bool
     */
    public function islogin()
    {
        $cookie = get_cookie(config('web.WEB_MMCOOKIE'));
        $ip = request()->ip();
        $microtime = microtime(true) * 1000;
        $microtime = explode('.', $microtime);
        $api_url = 'http://pub.alimama.com/overview/unionaccountinfo.json?t='.$microtime[0].'&_tb_token_=9ix3ygeZUln&_input_charset=utf-8';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $api_url);
        curl_setopt($ch, CURLOPT_REFERER, 'http://www.alimama.com/index.htm');
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Cookie:{' . $cookie['HTTPHEADER'] . '}'));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_MAXREDIRS, 2);
        $source = curl_exec($ch);
        curl_close($ch);
        $result_api = json_decode($source, true);
        if($result_api){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 抓取数据
     * @param $url
     * @return mixed
     */
    public function getHttpRequestWith($url){
        //阿里妈妈缓存处理
        $cookie = get_cookie(config('web.WEB_MMCOOKIE'));
        $api_url = $url;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $api_url);
        curl_setopt($ch, CURLOPT_REFERER, 'http://www.alimama.com/index.htm');
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Cookie:{' . $cookie['HTTPHEADER'] . '}'));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_MAXREDIRS, 2);
        $source = curl_exec($ch);
        curl_close($ch);
        $result = json_decode($source, true);
        return $result;
    }

}
